package src.address;
 
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPEnvelope;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

public class AddressMatchingServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        if (request.getParameter("wsdl") != null) {
            response.setContentType("text/xml");
            InputStream wsdl = this.getClass().getResourceAsStream("AddressMatchingService.wsdl");
            for (int c; (c = wsdl.read()) >= 0;) {
                response.getOutputStream().write(c);
            }
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        try {
            SOAPMessage soapRequest = 
                MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(
                    new MimeHeaders(), request.getInputStream());
                    
            MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
            SOAPFactory soapFactory = SOAPFactory.newInstance();
            SOAPMessage soapResponse = messageFactory.createMessage();
			
			SOAPEnvelope env = soapResponse.getSOAPPart().getEnvelope();
			env.addNamespaceDeclaration("xsd","http://www.w3.org/2001/XMLSchema");
			env.addNamespaceDeclaration("xsi","http://www.w3.org/2001/XMLSchema-instance");
			
            Address addressResponse = matchAddress(getAddress(soapRequest));
			SOAPElement matchAddress = soapResponse.getSOAPBody().addChildElement(
				soapFactory.createName("matchAddress", "asd", "urn:bigtelco:addressmatchingervice"));
			
			if (addressResponse.getMatched())
				matchAddress.addChildElement(soapFactory.createName("matched")).addTextNode("1").setAttribute("xsi:type","xsd:boolean");
			else
				matchAddress.addChildElement(soapFactory.createName("matched")).addTextNode("0").setAttribute("xsi:type","xsd:boolean");
			
			SOAPElement addressElement = matchAddress.addChildElement(soapFactory.createName("address"));
			addressElement.setAttribute("xsi:type","asd:address");
			addressElement.addChildElement(soapFactory.createName("street")).addTextNode(addressResponse.getStreet()).setAttribute("xsi:type","xsd:string");
			addressElement.addChildElement(soapFactory.createName("city")).addTextNode(addressResponse.getCity()).setAttribute("xsi:type","xsd:string");
			addressElement.addChildElement(soapFactory.createName("province")).addTextNode(addressResponse.getProvince()).setAttribute("xsi:type","xsd:string");
			addressElement.addChildElement(soapFactory.createName("postalCode")).addTextNode(addressResponse.getPostalCode()).setAttribute("xsi:type","xsd:string");
			addressElement.addChildElement(soapFactory.createName("country")).addTextNode(addressResponse.getCountry()).setAttribute("xsi:type","xsd:string");

            response.setContentType(SOAPConstants.SOAP_1_2_CONTENT_TYPE);
            soapResponse.writeTo(response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e);
        }
    }

    private synchronized Address matchAddress(Address address) {
    	if (address.getStreet().equals("3800 Finnerty Road") && address.getCity().equals("") && address.getPostalCode().equals("V8P") && address.getCountry().equals("Canada") && address.getProvince().equals("")) {
    		return new Address(true, "3800 Finnerty Road", "Victoria", "BC", "V8P 5C2", "Canada");
    	} else {
    		return new Address(false, "", "", "", "", "");
    	}
    }
    
    private Address getAddress(SOAPMessage soapRequest) throws Exception {
		String street = soapRequest.getSOAPBody().getChildNodes().item(0).getChildNodes().item(0).getChildNodes().item(0).getTextContent();
		String city = soapRequest.getSOAPBody().getChildNodes().item(0).getChildNodes().item(0).getChildNodes().item(1).getTextContent();
		String province = soapRequest.getSOAPBody().getChildNodes().item(0).getChildNodes().item(0).getChildNodes().item(2).getTextContent();
		String postalCode = soapRequest.getSOAPBody().getChildNodes().item(0).getChildNodes().item(0).getChildNodes().item(3).getTextContent();
		String country = soapRequest.getSOAPBody().getChildNodes().item(0).getChildNodes().item(0).getChildNodes().item(4).getTextContent();
		
		return new Address(false, street, city, province, postalCode, country);
    }
}
